package com.software.myopiachildren;

import android.Manifest;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.software.myopiachildren.adapter.MainFragmentAdapter;
import com.software.myopiachildren.base.BaseActivity;
import com.software.myopiachildren.bean.BaseInfo;
import com.software.myopiachildren.bean.SensorInfo;
import com.software.myopiachildren.content.Constant;
import com.software.myopiachildren.fragment.ConnectFragment;
import com.software.myopiachildren.fragment.SetFragment;
import com.software.myopiachildren.http.HostType;
import com.software.myopiachildren.http.HttpApi2;
import com.software.myopiachildren.service.LocalService;
import com.software.myopiachildren.utils.NotificationUtils;
import com.software.myopiachildren.utils.ToastUtil;
import com.software.myopiachildren.utils.perm.NetworkUtils;
import com.software.myopiachildren.utils.perm.PermissionsUtils;
import com.software.myopiachildren.utils.sp.SP;
import com.software.myopiachildren.view.SlideViewPager;
import com.tencent.bugly.beta.Beta;
import com.tencent.bugly.beta.download.DownloadListener;
import com.tencent.bugly.beta.download.DownloadTask;

import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import timber.log.Timber;

public class MainActivity001 extends BaseActivity implements SensorEventListener {
    private static final String TAG = "MainActivity";

    @BindView(R.id.vp_main_content)
    SlideViewPager mVp;
    @BindView(R.id.rb_item1)
    RadioButton mRb1;
    @BindView(R.id.rb_item2)
    RadioButton mRb2;
    @BindView(R.id.rg_main)
    RadioGroup mRg;

    private List<Fragment> mFragment = new ArrayList<>();


    // 传感器
    private SensorManager sensorManager;
    private Sensor sensor;
    private static long startTime = 0L;// 起点时间
    private int duration = 5000;// 每次采样持续时间
    ArrayList<String> temp_record = new ArrayList(); // 暂存5秒内的数据
    ArrayList<Float> direction_record = new ArrayList(); // 暂存5秒内的数据
    ArrayList<SensorInfo> part_record = new ArrayList(); // 暂存5秒内的数据(存三个数值)
    private float[] data = {0.0F, 0.0F, 0.0F};// 接收传感器数据
    StringBuilder localStringBuilder;

    private int isGathering = 0;  // 1:有满足条件  2：5秒收集
    private MediaPlayer mediaPlayer;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_main;
    }

    @Override
    public void initView() {
        // Fragment操作
        mFragment.add(new ConnectFragment());
        mFragment.add(new SetFragment());
        mVp.setOffscreenPageLimit(mFragment.size());
        mVp.setAdapter(new MainFragmentAdapter(getSupportFragmentManager(), mFragment));
        initListener();


        /**
         *  传感器获取频率
         *  Sensor.TYPE_ACCELEROMETER   加速度传感器
         *  Sensor.TYPE_GYROSCOPE   陀螺仪传感器
         *  Sensor.TYPE_LIGHT   环境光线传感器
         *  Sensor.TYPE_MAGNETIC_FIELD   电磁场传感器
         *  Sensor.TYPE_ORIENTATION  方向传感器
         *  Sensor.TYPE_PRESSURE   压力传感器
         *  Sensor.TYPE_PROXIMITY   距离传感器
         *  Sensor.TYPE_TEMPERATURE   温度传感器
         *
         *  传感器获取频率
         *  SensorManager.SENSOR_DEPLAY_FASTEST   最灵
         *  SensorManager.SENSOR_DEPLAY_GAME   游戏使用
         *  SensorManager.SENSOR_DEPLAY_NORMAL   正常频率(较慢)
         *  SensorManager.SENSOR_DEPLAY_UI     最慢(横和竖)
         *
         */
        //获取SensorManager实例
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        //获取Sensor实例
        sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
        //注册滚动事件
        sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_UI);

    }

    @Override
    public void initData() {
        getVersionDownload(); // 新版本下载
        getCheckVersion(); // 检查版本更新
        getPermissions();  // 权限管理
    }


    @Override
    protected void onDestroy() {
        // 解除注册
        sensorManager.unregisterListener(this);
        // 解除播放器
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }


    /**
     * 底部监听事件
     */
    private void initListener() {
        mRg.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId) {
                case R.id.rb_item1:
                    mVp.setCurrentItem(0);
                    mRg.setBackgroundColor(getResources().getColor(R.color.color_bg_style1));
//                    EB.post(new EbData(10));
                    break;

                case R.id.rb_item2:
                    mVp.setCurrentItem(1);
                    mRg.setBackgroundColor(getResources().getColor(R.color.color_bg_style));
//                    EB.post(new EbData(11));
//                    EB.post(new EbData(12));
                    break;
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        getSupportFragmentManager().getFragments();
        if (getSupportFragmentManager().getFragments().size() > 0) {
            List<Fragment> fragments = getSupportFragmentManager().getFragments();
            for (Fragment mFragment : fragments) {
                mFragment.onActivityResult(requestCode, resultCode, data);
            }
        }
    }


    /**
     * 发送警报
     */
    private void getAlert() {
        String device_code = new SP().load(Constant.DEVICE_CODE, "");
        String jwt_token = new SP().load(Constant.USER_JWT_TOKEN, "");
        if (NetworkUtils.isConnected(MainActivity001.this)) {
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", jwt_token);

            Map<String, String> params = new HashMap<>();
            params.put("device_code", device_code);
            params.put("type", 1 + "");

            HttpApi2.getApiService(HostType.TELE_CONFIG).getAlert(headers, params).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<BaseInfo>() {
                        @Override
                        public void onSubscribe(Subscription s) {
                            s.request(Long.MAX_VALUE);
                        }

                        @Override
                        public void onNext(BaseInfo baseInfo) {
                            try {
                                Log.e(TAG, "===baseInfo:" + baseInfo.toString());
                                if (baseInfo.getCode().equals(Constant.CODE_SUCCESS)) {
                                    ToastUtil.showShort(baseInfo.getMsg());
                                } else {
                                    ToastUtil.showShort(baseInfo.getMsg());
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onError(Throwable t) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        } else {
            ToastUtil.showShort(getResources().getString(R.string.network_fial_message));
        }
    }

    /**
     * 激活设备
     */
    private void getActivateDevice() {
        String device_code = new SP().load(Constant.DEVICE_CODE, "");
        String jwt_token = new SP().load(Constant.USER_JWT_TOKEN, "");
        if (NetworkUtils.isConnected(MainActivity001.this)) {
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", jwt_token);

            Map<String, String> params = new HashMap<>();
            params.put("device_code", device_code);

            HttpApi2.getApiService(HostType.TELE_CONFIG).getActivateDevice(headers, params).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<BaseInfo>() {
                        @Override
                        public void onSubscribe(Subscription s) {
                            s.request(Long.MAX_VALUE);
                        }

                        @Override
                        public void onNext(BaseInfo baseInfo) {
                            try {
                                Log.e(TAG, "===baseInfo:" + baseInfo.toString());
                                if (baseInfo.getCode().equals(Constant.CODE_SUCCESS)) {
                                    ToastUtil.showShort(baseInfo.getMsg());
                                } else {
                                    ToastUtil.showShort(baseInfo.getMsg());
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onError(Throwable t) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        } else {
            ToastUtil.showShort(getResources().getString(R.string.network_fial_message));
        }
    }


    /**
     * SensorEventListener接口 onSensorChanged方法
     */
    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        Log.e(TAG, "======方位角：" + (float) (Math.round(sensorEvent.values[0] * 100)) / 100);
        Log.e(TAG, "======倾斜角：" + (float) (Math.round(sensorEvent.values[1] * 100)) / 100);
        Log.e(TAG, "======滚动角：" + (float) (Math.round(sensorEvent.values[2] * 100)) / 100);

        data[0] = sensorEvent.values[0];
        data[1] = sensorEvent.values[1];
        data[2] = sensorEvent.values[2];
//        tempRecorder(data);


        // 方案二 ：结合三个坐标角度判断
        //   满足条件：values[0] , values[1] , values[2]
        //   满足条件1：任意数值，-90-90， -30-30
        //   满足条件2：任意数值，-30-30， -90-90
        try {
            float direction_bear = (float) (Math.round(sensorEvent.values[1] * 100)) / 100;
            float direction_angle = (float) (Math.round(sensorEvent.values[1] * 100)) / 100;
            float direction_scroll = (float) (Math.round(sensorEvent.values[1] * 100)) / 100;
            if (isGathering == 0) {
                if (!(((direction_angle > -90 && direction_angle < 90) && (direction_scroll > -30 && direction_scroll < 30)) ||
                        ((direction_angle > -30 && direction_angle < 30) && (direction_scroll > -90 && direction_scroll < 90)))) {
                    Log.e(TAG, "======：-111111");
                    isGathering = 1;
                    startTime = System.currentTimeMillis();// 获取系统当前时间
                }
            } else if (isGathering == 1) {
                if (System.currentTimeMillis() - startTime <= duration) {
                    part_record.add(new SensorInfo(direction_bear, direction_angle, direction_scroll));
                    Log.e(TAG, "======：000000");
                } else {
                    isGathering = 2;
                    int totalAngle = part_record.size();
                    int fillAngle = 0;
                    if (totalAngle > 0) {
                        for (int i = 0; i < totalAngle; i++) {
                            if (!(((part_record.get(i).getDirection_angle() > -90 && part_record.get(i).getDirection_angle() < 90) && (part_record.get(i).getDirection_scroll() > -30 && part_record.get(i).getDirection_scroll() < 30)) ||
                                    ((part_record.get(i).getDirection_angle() > -30 && part_record.get(i).getDirection_angle() < 30) && (part_record.get(i).getDirection_scroll() > -90 && part_record.get(i).getDirection_scroll() < 90)))) {
                                fillAngle++; // 满足条件的就增加一个
                                Log.e(TAG, "======：111111");
                            }
                        }

                        // 判断收集数据80%符合预警条件的就及时预警
                        if (fillAngle / totalAngle > 0.1) {
                            // 预警提示音
                            int warning_type = new SP().load(Constant.WARNING_TYPE, 1);
                            if (warning_type == 1) { //系统提示音
                                Log.e(TAG, "======：222222");
                                if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                                    mediaPlayer.stop();
                                    mediaPlayer.release();
                                    mediaPlayer = null;
                                }
                                mediaPlayer = MediaPlayer.create(MainActivity001.this, R.raw.moren);
                                mediaPlayer.start();
                               /* mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                                    @Override
                                    public void onCompletion(MediaPlayer mp) {
                                        mediaPlayer.release();
                                        mediaPlayer = null;
                                    }
                                });*/
                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        // 5秒后警铃关闭，清空暂存数据，重新收集
                                        mediaPlayer.stop();
                                        mediaPlayer.release();
                                        mediaPlayer = null;
                                        startTime = 0L;
                                        part_record.clear();
                                        isGathering = 0;
                                    }
                                }, 5000);
                            } else if (warning_type == 2) { //用户录音
                                Log.e(TAG, "======：333333");
                                if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                                    mediaPlayer.stop();
                                    mediaPlayer.release();
                                    mediaPlayer = null;
                                }
                                mediaPlayer = new MediaPlayer();
                                mediaPlayer.setDataSource(new SP().load(Constant.RECORD_PATH_ABSOULT, ""));
                                mediaPlayer.prepare();
                                mediaPlayer.start();
                                /*mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                                    @Override
                                    public void onCompletion(MediaPlayer mp) {
                                        mediaPlayer.release();
                                        mediaPlayer = null;
                                    }
                                });*/

                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        // 5秒后警铃关闭，清空暂存数据，重新收集
                                        mediaPlayer.stop();
                                        mediaPlayer.release();
                                        mediaPlayer = null;
                                        startTime = 0L;
                                        part_record.clear();
                                        isGathering = 0;
                                    }
                                }, 5000);
                            }
                        } else {
                            // 清空暂存数据，重新收集
                            startTime = 0L;
                            part_record.clear();
                            isGathering = 0;
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 方案一 ：单个判断倾斜度(不太精确)
        /*try {
            float direction_angle = (float) (Math.round(sensorEvent.values[1] * 100)) / 100;
            if (isGathering == 0) {
                if (direction_angle > 30 || direction_angle < -30) {
                    Log.e(TAG, "======：-111111");
                    isGathering = 1;
                    startTime = System.currentTimeMillis();// 获取系统当前时间
                }
            } else if (isGathering == 1) {
                if (System.currentTimeMillis() - startTime <= duration) {
                    direction_record.add(direction_angle);
                    Log.e(TAG, "======：000000");
                } else {
                    isGathering = 2;

                    int totalAngle = direction_record.size();
                    int fillAngle = 0;
                    if (totalAngle > 0) {
                        for (int i = 0; i < totalAngle; i++) {
                            if ((direction_angle > 30 && direction_angle < 60) || (direction_angle > -60 && direction_angle < -30)) {
                                fillAngle++; // 满足条件的就增加一个
                                Log.e(TAG, "======：111111");
                            }
                        }

                        // 判断收集数据80%符合预警条件的就及时预警
                        if (fillAngle / totalAngle > 0.8) {
                            // 预警提示音
                            int warning_type = new SP().load(Constant.WARNING_TYPE, 1);
                            if (warning_type == 1) { //系统提示音
                                Log.e(TAG, "======：222222");
                                if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                                    mediaPlayer.stop();
                                    mediaPlayer.release();
                                    mediaPlayer = null;
                                }
                                mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.moren);
                                mediaPlayer.start();
                               *//* mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                                    @Override
                                    public void onCompletion(MediaPlayer mp) {
                                        mediaPlayer.release();
                                        mediaPlayer = null;
                                    }
                                });*//*
                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        // 5秒后警铃关闭，清空暂存数据，重新收集
                                        mediaPlayer.stop();
                                        mediaPlayer.release();
                                        mediaPlayer = null;
                                        startTime = 0L;
                                        direction_record.clear();
                                        isGathering = 0;
                                    }
                                }, 5000);
                            } else if (warning_type == 2) { //用户录音
                                Log.e(TAG, "======：333333");
                                if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                                    mediaPlayer.stop();
                                    mediaPlayer.release();
                                    mediaPlayer = null;
                                }
                                mediaPlayer = new MediaPlayer();
                                mediaPlayer.setDataSource(new SP().load(Constant.RECORD_PATH_ABSOULT, ""));
                                mediaPlayer.prepare();
                                mediaPlayer.start();
                                *//*mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                                    @Override
                                    public void onCompletion(MediaPlayer mp) {
                                        mediaPlayer.release();
                                        mediaPlayer = null;
                                    }
                                });*//*

                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        // 5秒后警铃关闭，清空暂存数据，重新收集
                                        mediaPlayer.stop();
                                        mediaPlayer.release();
                                        mediaPlayer = null;
                                        startTime = 0L;
                                        direction_record.clear();
                                        isGathering = 0;
                                    }
                                }, 5000);
                            }
                        } else {
                            // 清空暂存数据，重新收集
                            startTime = 0L;
                            direction_record.clear();
                            isGathering = 0;
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }*/
    }


    /**
     * SensorEventListener接口 onAccuracyChanged方法
     */
    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {

    }


    /**
     * 将采集到的数据放入动态数组
     *
     * @param data
     */
    private void tempRecorder(float[] data) {
        temp_record = new ArrayList();
        localStringBuilder = new StringBuilder();
        for (int i = 0; i < 3; i++) {
            localStringBuilder.append(String.valueOf(data) + " ");
            // 向localStringBuilder中添加一条数据
        }
        localStringBuilder.append("\t");
        temp_record.add(localStringBuilder.toString());
    }


    // 再按一次退出
    private long mExitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                ToastUtil.showShort(getResources().getString(R.string.s_btn_exit));
                mExitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /*****  权限管理、版本管理start *****/
    /**
     * 权限管理
     */
    private void getPermissions() {
        // 权限管理（设置需要打开的所有权限）
        String[] permissions = new String[]{
                Manifest.permission.CAMERA,
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.READ_EXTERNAL_STORAGE, // 读取内存权限
                Manifest.permission.WRITE_EXTERNAL_STORAGE}; // 写入内存权限
//        PermissionsUtils.showSystemSetting = false;//是否支持显示系统设置权限设置窗口跳转
        //这里的this不是上下文，是Activity对象！
        PermissionsUtils.getInstance().chekPermissions(this, permissions, permissionsResult);
    }

    //创建监听权限的接口对象（权限设置）
    PermissionsUtils.IPermissionsResult permissionsResult = new PermissionsUtils.IPermissionsResult() {
        @Override
        public void passPermissons() {
            Log.e(TAG, "====:权限通过，开始操作");
            // （权限通过后）开始操作

            // 开启后台进程守护
            startService(new Intent(MainActivity001.this, LocalService.class));

        }

        @Override
        public void forbitPermissons() {
            Log.e(TAG, "====:权限不通过，重新授权");
//            finish();
        }
    };

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //就多一个参数this
        PermissionsUtils.getInstance().onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    // 检查新版本
    private void getCheckVersion() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Beta.strToastYourAreTheLatestVersion = "";
                Beta.checkUpgrade();
            }
        }, 700);
    }

    // 版本下载更新
    private void getVersionDownload() {
        Beta.registerDownloadListener(new DownloadListener() {
            @Override
            public void onReceive(DownloadTask downloadTask) {
                Timber.tag(Constant.TAG).e("onReceive");
                NotificationUtils.notificationMsg(MainActivity001.this, Constant.VERSION_UPGRADE + "", getResources().getString(R.string.app_name),
                        getResources().getString(R.string.s_version_download) + (int) (downloadTask.getSavedLength() * 100 / downloadTask.getTotalLength()) + "%", null);
            }

            @Override
            public void onCompleted(DownloadTask downloadTask) {
                Timber.tag(Constant.TAG).e("onCompleted:" + downloadTask.getSaveFile());
                PendingIntent pi = PendingIntent.getActivity(MainActivity001.this, 0, getInstallIntent(downloadTask.getSaveFile()), 0);
                NotificationUtils.notificationMsg(MainActivity001.this, Constant.VERSION_UPGRADE + "", getResources().getString(R.string.app_name),
                        getResources().getString(R.string.s_version_download_success), pi);
            }

            @Override
            public void onFailed(DownloadTask downloadTask, int i, String s) {
                Timber.tag(Constant.TAG).e("onFailed" + s);
                NotificationUtils.notificationMsg(MainActivity001.this, Constant.VERSION_UPGRADE + "", getResources().getString(R.string.app_name),
                        getResources().getString(R.string.s_version_download_failure), null);
            }
        });
    }

    private Intent getInstallIntent(File saveFile) {
        Intent install = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= 24) { //判读版本是否在7.0以上
            Uri apkUri = FileProvider.getUriForFile(getApplicationContext(), BuildConfig.APPLICATION_ID + ".fileProvider", saveFile);//在AndroidManifest中的android:authorities值
            install = new Intent(Intent.ACTION_VIEW);
            install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
            install.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            install.setDataAndType(Uri.fromFile(saveFile), "application/vnd.android.package-archive");
            install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        return install;
    }

    /*****  权限管理、版本管理stop *****/

}